import {
  ADD_MISSION,
  POP_MISSION,
  SUBMIT_MISSION,
  SUBMIT_PLAN,
  SUBMIT_PLAN_SUCCESS,
  CANCEL_OVERRIDE_PLAN
} from "../constants/makePlan";

const INIT_STATE = {
  submitedMission: [],
  unsubmitedPlans: [null, []]
};

export default function makePlan(state = INIT_STATE, action) {
  switch (action.type) {
    case ADD_MISSION:
      return { ...state, addMission: true };
    case SUBMIT_MISSION:
      if (action.payload === undefined) return { ...state, addMission: false };
      else {
        let newSubmitedMission = [...state.submitedMission];
        newSubmitedMission.push(action.payload);
        return {
          ...state,
          submitedMission: newSubmitedMission,
          addMission: false
        };
      }
    case POP_MISSION:
      let newSubmitedMission = [...state.submitedMission];
      newSubmitedMission.pop();
      return { ...state, submitedMission: newSubmitedMission };
    case SUBMIT_PLAN:
      let resData = action.payload.data.data;
      return resData[1].length !== 0
        ? {
            ...state,
            unsubmitedPlans: resData,
            submitedMission: [],
            submitedPlan: true
          }
        : {
            ...state,
            unsubmitedPlans: [null, []],
            submitedPlan: true,
            submitedMission: []
          };
    case SUBMIT_PLAN_SUCCESS:
      let { submitedPlan, ...newState } = state;
      return { ...newState };
    case CANCEL_OVERRIDE_PLAN:
      let { unsubmitedPlans: unsubmited, ...cancelOverrideState } = state;
      return { ...cancelOverrideState };
    default:
      return state;
  }
}
